import request from '@/utils/request'
import { CartItemResponse } from '@/type/cart'

const api_name = '/orders'

// 订单项类型定义
interface OrderItem {
  productId: number
  name: string
  imageUrl: string
  price: number
  quantity: number
}

// 创建订单请求参数类型
interface CreateOrderRequest {
  orderItemDTOS: OrderItem[]
  couponIds: string[]
}

// 订单快照
interface OrderSnapshot {
  orderNo: string
  userId: number
}

interface OrderRenewDTO {
  orderNo: string
  address: string
  phone: string
  name: string
  remark: string
}

export interface OrderResponse {
  orderNo: string
  userId: number
  totalAmount: number
  status: number
  address: string
  createTime: string
  productList: ProductItem[]
  couponIds: string[]
}

export interface ProductItem {
  id: number
  name: string
  imageUrl: string
  price: number
  sales: number
  comments: number
  isAd: boolean
  description: string
  tags: string
  quantity: number
}

export interface OrderListQuery {
  pageNo: number
  pageSize: number
  status?: number
  sortBy?: string
  isAsc?: boolean
}

export interface OrderListResponse {
  total: number
  pages: number
  list: OrderResponse[]
}

export interface OrderResponse {
  orderNo: string
  name: string
  phone: string
  address: string
  status: number
  createTime: string
}

export default {
  /**
   * 创建订单
   * @param orderItemDTOS 选中的购物车商品列表
   * @param couponIds 优惠券ID列表
   * @returns 返回订单快照OrderSnapshot
   */
  createOrder(orderItemDTOS: CartItemResponse[], couponIds: string[]) {
    const requestData: CreateOrderRequest = {
      orderItemDTOS: orderItemDTOS.map((orderItemDTO) => ({
        productId: orderItemDTO.productId,
        name: orderItemDTO.name,
        imageUrl: orderItemDTO.imageUrl,
        price: orderItemDTO.price,
        quantity: orderItemDTO.quantity,
      })),
      couponIds
    }

    return request({
      url: `${api_name}/create`,
      method: 'post',
      data: requestData,
    })
  },

  /**
   * 根据订单编号获取订单详情
   * @param orderNo 订单编号
   * @returns 返回订单详情OrderResponse
   */
  getOrderDetail(orderNo: string) {
    return request({
      url: `${api_name}/query`,
      method: 'get',
      params: { orderNo },
    })
  },

  /**
   * 更新订单信息
   * @param order 订单信息
   * @returns 不返回值
   */
  updateOrder(order: OrderRenewDTO) {
    return request({
      url: `${api_name}/update`,
      method: 'put',
      data: order,
    })
  },

  /**
   * 查询订单列表
   * @param query 查询参数
   * @returns 订单列表OrderListResponse
   */
  queryOrderList(query: OrderListQuery) {
    return request({
      url: `${api_name}/list`,
      method: 'get',
      params: query,
    })
  },

  /**
   * 查询订单详情
   * @param orderNo 订单编号
   * @returns 订单详情OrderResponse
   */
  getOrderItem(orderNo: string) {
    return request({
      url: `${api_name}/getOrderItem`,
      method: 'get',
      params: { orderNo },
    })
  },
}